package com.ruoyi.mall.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.mall.domain.Goods;
import com.ruoyi.mall.domain.ProductSkus;
import com.ruoyi.mall.domain.ProductSpecValues;
import com.ruoyi.mall.domain.Specifications;
import com.ruoyi.mall.mapper.GoodsMapper;
import com.ruoyi.mall.mapper.ProductSkusMapper;
import com.ruoyi.mall.mapper.ProductSpecValuesMapper;
import com.ruoyi.mall.mapper.SpecificationsMapper;
import com.ruoyi.mall.service.IGoodsService;
import com.ruoyi.userManage.mapper.UserMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品信息Controller
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@RestController
@RequestMapping("/shangpin/Goods")
public class GoodsController extends BaseController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private UserMapper usersMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private SpecificationsMapper specificationsMapper;
    @Autowired
    private ProductSpecValuesMapper productSpecValuesMapper;
    @Autowired
    private ProductSkusMapper productSkusesMapper;

    /**
     * 查询商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('mall:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(Goods goods) {
        goods.setIsDelete(0L);
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        for (Goods goods1 : list) {
            String name = usersMapper.selClassNameId(goods1.getGatgoryId());
            if (StringUtils.isNotEmpty(name)) {
                goods1.setGatgoryName(name);
            } else {
                goods1.setGatgoryName("类目已删除");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('mall:goods:export')")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Goods goods) {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        util.exportExcel(response, list, "商品信息数据");
    }


    /**
     * 获取商品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:goods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        Goods goods = goodsService.selectGoodsById(id.longValue());
        String name = usersMapper.selClassNameId(goods.getGatgoryId());
        if (StringUtils.isNotEmpty(name)) {
            goods.setGatgoryName(name);
        } else {
            goods.setGatgoryName("分类已删除");
        }
        List<Specifications> specifications = goodsMapper.selSpec(goods.getId().intValue());
        goods.setSpecificationsList(specifications);
        for (Specifications specification : goods.getSpecificationsList()) {
            List<ProductSpecValues> productSpecValues = goodsMapper.selProd(specification.getSpecId().intValue());
            specification.setSpecValuesList(productSpecValues);
        }
        List<ProductSkus> skuses = new ArrayList<>();
        List<ProductSpecValues> productSpecValues = goods.getSpecificationsList().get(0).getSpecValuesList();
        List<ProductSpecValues> productSpecValues1 = goods.getSpecificationsList().get(1).getSpecValuesList();
        for (ProductSpecValues productSpecValue : productSpecValues) {
            for (ProductSpecValues specValues : productSpecValues1) {
                String sku_code = productSpecValue.getSpecValueId() + "-" + specValues.getSpecValueId();
                logger.info("sku_code=" + sku_code);
                ProductSkus productSkus = goodsMapper.selSkuCode(sku_code);
                productSkus.setSpecValue(productSpecValue.getSpecValueId().intValue());
                productSkus.setSpecValueName(productSpecValue.getSpecValue());
                productSkus.setSpecValue1(specValues.getSpecValueId().intValue());
                productSkus.setSpecValue1Name(specValues.getSpecValue());
                skuses.add(productSkus);
            }
        }
        goods.setProductSkuses(skuses);

        return success(goods);
    }

    /**
     * 新增商品信息
     */
    @PreAuthorize("@ss.hasPermi('mall:goods:add')")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Goods goods) {
        Integer count = goodsMapper.selCount(goods.getName());
        if (count > 0) {
            return error("商品名称重复！");
        }
        goodsService.insertGoods(goods);
        //获得规格
        List<Specifications> specifications = goods.getSpecificationsList();
        for (Specifications specification : specifications) {
            //新规格
            Specifications newSpecification = new Specifications();
            newSpecification.setGoodsId(goods.getId());
            newSpecification.setSpecName(specification.getSpecName());
            newSpecification.setCreateTime(new Date());
            newSpecification.setUpdateTime(new Date());
            specificationsMapper.insertSpecifications(newSpecification);
            List<ProductSpecValues> productSpecValues = specification.getSpecValuesList();
            for (ProductSpecValues productSpecValue : productSpecValues) {
                //新规格值
                ProductSpecValues newproductSpecValue = new ProductSpecValues();
                newproductSpecValue.setSpecId(newSpecification.getSpecId());
                newproductSpecValue.setSpecValue(productSpecValue.getSpecValue());
                newproductSpecValue.setCreateTime(new Date());
                newproductSpecValue.setUpdateTime(new Date());
                productSpecValuesMapper.insertProductSpecValues(newproductSpecValue);
            }
        }
        //传入的规格值
        List<ProductSkus> skuses = goods.getProductSkuses();
        for (ProductSkus skus : skuses) {
            Integer valueid = goodsMapper.selProdId(goods.getId().intValue(), skus.getSpecValueName());
            Integer valueids = goodsMapper.selProdId(goods.getId().intValue(), skus.getSpecValue1Name());
            String sku_code = valueid + "-" + valueids;
            logger.info("新增sku_code=" + sku_code);
            ProductSkus productSkus = new ProductSkus();
            //新增sku
            productSkus.setProductId(goods.getId());
            productSkus.setSkuCode(sku_code);
            productSkus.setCreateTime(new Date());
            productSkus.setUpdateTime(new Date());
            productSkus.setValueid(valueid.longValue());
            productSkus.setValueids(valueids.longValue());
            productSkus.setImg(skus.getImg());
            productSkus.setStock(skus.getStock());
            productSkus.setPrice(skus.getPrice());
            productSkus.setTicketNum(skus.getTicketNum());
            productSkusesMapper.insertProductSkus(productSkus);
        }
        return toAjax(1);
    }

    /**
     * 修改商品信息
     */
    @PreAuthorize("@ss.hasPermi('mall:goods:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Goods goods) {
        List<Specifications> specifications = goods.getSpecificationsList();
        //获得修改后的全体规格ID
        List<Integer> integerggid = new ArrayList<>();
        //获得修改后的全体规格值ID
        List<Integer> integerggzid = new ArrayList<>();
        //获取传入的规格名称数据
        for (Specifications specification : specifications) {
            if (specification.getSpecId() != null && specification.getSpecId() != 0) {
                //规则ID存在 获得规则信息
                Specifications oldSpec = goodsMapper.selOldSpec(specification.getSpecId().intValue());
                integerggid.add(oldSpec.getSpecId().intValue());
                if (specification.getGoodsId().equals(oldSpec.getGoodsId()) && !specification.getSpecName().equals(oldSpec.getSpecName())) {
                    //规格名称变更
                    goodsMapper.updateSpec(specification.getSpecId().intValue(), specification.getSpecName(), new Date());
                }
                for (ProductSpecValues productSpecValues : specification.getSpecValuesList()) {
                    if (productSpecValues.getSpecValueId() != null && productSpecValues.getSpecValueId() != 0) {
                        //规则值ID存在 获得规则值信息
                        ProductSpecValues oldSpecValue = goodsMapper.selOldSpecValue(productSpecValues.getSpecValueId().intValue());
                        integerggzid.add(oldSpecValue.getSpecValueId().intValue());
                        if (productSpecValues.getSpecValueId().equals(oldSpecValue.getSpecValueId()) && !productSpecValues.getSpecValue().equals(oldSpecValue.getSpecValue())) {
                            //规则值名称变更
                            goodsMapper.updateSpecValue(productSpecValues.getSpecValueId().intValue(), productSpecValues.getSpecValue(), new Date());
                        }
                    } else {
                        ProductSpecValues newproductSpecValue = new ProductSpecValues();
                        newproductSpecValue.setSpecId(productSpecValues.getSpecId());
                        newproductSpecValue.setSpecValue(productSpecValues.getSpecValue());
                        newproductSpecValue.setCreateTime(new Date());
                        newproductSpecValue.setUpdateTime(new Date());
                        productSpecValuesMapper.insertProductSpecValues(newproductSpecValue);
                        integerggzid.add(newproductSpecValue.getSpecValueId().intValue());
                    }
                }
            } else {
                //新规格
                Specifications newSpecification = new Specifications();
                newSpecification.setSpecName(specification.getSpecName());
                newSpecification.setGoodsId(specification.getGoodsId());
                newSpecification.setCreateTime(new Date());
                newSpecification.setUpdateTime(new Date());
                specificationsMapper.insertSpecifications(newSpecification);
                integerggid.add(newSpecification.getSpecId().intValue());
                for (ProductSpecValues productSpecValues : specification.getSpecValuesList()) {
                    ProductSpecValues newproductSpecValue = new ProductSpecValues();
                    newproductSpecValue.setSpecId(newSpecification.getSpecId());
                    newproductSpecValue.setSpecValue(productSpecValues.getSpecValue());
                    newproductSpecValue.setCreateTime(new Date());
                    newproductSpecValue.setUpdateTime(new Date());
                    productSpecValuesMapper.insertProductSpecValues(newproductSpecValue);
                    integerggzid.add(newproductSpecValue.getSpecValueId().intValue());
                }
            }
        }
        //删除旧的规格ID
        goodsMapper.deleGGid(goods.getId().intValue(), integerggid);
        //删除旧的规格值ID
        goodsMapper.deleGGZid(goods.getId().intValue(), integerggzid);
        //获得修改后的全体skuid
        List<Integer> integerskus = new ArrayList<>();
        //传入的规格值
        List<ProductSkus> skuses = goods.getProductSkuses();
        for (ProductSkus skus : skuses) {
            Integer valueid = goodsMapper.selProdId(goods.getId().intValue(), skus.getSpecValueName());
            Integer valueids = goodsMapper.selProdId(goods.getId().intValue(), skus.getSpecValue1Name());
            String sku_code = valueid + "-" + valueids;
            logger.info("当前查询sku_code=" + sku_code);
            //查询sku_code
            ProductSkus productSkus = goodsMapper.selSkuCode(sku_code);
            if (productSkus == null) {
                productSkus = new ProductSkus();
                //新增sku
                productSkus.setProductId(goods.getId());
                productSkus.setSkuCode(sku_code);
                productSkus.setCreateTime(new Date());
                productSkus.setUpdateTime(new Date());
                productSkus.setValueid(valueid.longValue());
                productSkus.setValueids(valueids.longValue());
                productSkus.setImg(skus.getImg());
                productSkus.setStock(skus.getStock());
                productSkus.setPrice(skus.getPrice());
                productSkus.setTicketNum(skus.getTicketNum());
                productSkusesMapper.insertProductSkus(productSkus);
                integerskus.add(productSkus.getSkuId().intValue());
            } else {
                //修改sku内容
                productSkus.setImg(skus.getImg());
                productSkus.setStock(skus.getStock());
                productSkus.setPrice(skus.getPrice());
                productSkus.setTicketNum(skus.getTicketNum());
                productSkus.setUpdateTime(new Date());
                productSkusesMapper.updateProductSkus(productSkus);
                integerskus.add(productSkus.getSkuId().intValue());
            }
        }
        //删除旧的sukid
        goodsMapper.deleSku(goods.getId().intValue(), integerskus);
        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除商品信息
     */
    @PreAuthorize("@ss.hasPermi('mall:goods:remove')")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
//        return toAjax(goodsService.deleteGoodsByIds(ids));
        for (Integer id : ids) {
            Goods object = new Goods();
            object.setId(id.longValue());
            object.setIsDelete(1L);
            goodsService.updateGoods(object);
        }
        return toAjax(1);
    }
}
